package com.yh.lq.robot;

import com.alibaba.fastjson.JSONObject;
import com.yh.lq.utils.AesUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

/**
 * 消息发送不用关心结果，本身就什么都没返回
 */
@Slf4j
class ApiMessageSender extends Thread implements ApiSender{
    private final WebSocketSession apiSession;
    private String robotSecretKey;
    private Long apiTimeout;
    private JSONObject responseJSON;


    ApiMessageSender(WebSocketSession apiSession,String robotSecretKey,Long apiTimeout) {
        this.apiSession = apiSession;
        this.robotSecretKey = robotSecretKey;
        this.apiTimeout = apiTimeout;
    }

    @Override
    public JSONObject sendApiJson(JSONObject apiJSON) throws Exception {
        log.debug("send msg:{}",apiJSON);
        String sendMsg=apiJSON.toJSONString();
        if(!StringUtils.isEmpty(robotSecretKey)){
            sendMsg= AesUtil.aesEncrypt(sendMsg,robotSecretKey);
        }
        synchronized (apiSession){
            apiSession.sendMessage(new TextMessage(sendMsg));
        }
        synchronized (this){
            this.wait(apiTimeout);
        }
        return responseJSON;
    }

    void onReceiveJson(JSONObject responseJSON) {
        this.responseJSON = responseJSON;
        synchronized (this) {
            this.notify();
        }
    }

}
